<?php
/**
 * 二维码
 */
namespace Lib;

class Qrcode
{
    /**
     * 生成图片二维码
     *
     * @param string $value 二维码内容， 如url地址
     * @param bool $logo logo图片
     * @param int $size 二维码大小
     * @return string
     */
    public static function img($value = '', $logo = false, $size = 8)
    {
        require_once 'Qrcode/Qrcode.php';

        $tmpName = rtrim($_SERVER['SRV_NCACHE_DIR'], '/') . '/' . md5($value) . '.png';

        $errorCorrectionLevel = 'Q'; //容错级别
        $matrixPointSize      = $size; //生成图片大小
        //生成二维码图片
        $res = \QRcode::png($value, $tmpName, $errorCorrectionLevel, $matrixPointSize, 2, true);
        $QR  = $tmpName; //已经生成的原始二维码图
		if( empty($logo) )
            $logo = dirname(THINK_PATH).'/Public/images/fg_logo.jpg';
        ob_start();
        if ($logo !== false) {
            $QR             = imagecreatefromstring(file_get_contents($QR));
            $logo           = imagecreatefromstring(file_get_contents($logo));
            $QR_width       = imagesx($QR); //二维码图片宽度
            $QR_height      = imagesy($QR); //二维码图片高度
            $logo_width     = imagesx($logo); //logo图片宽度
            $logo_height    = imagesy($logo); //logo图片高度
            $logo_qr_width  = $QR_width / 5;
            $scale          = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width     = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
            //输出图片
            // Header("Content-type: image/png");
            ImagePng($QR);
        } else {
            //输出图片
            // Header("Content-type: image/png");
            readfile($tmpName);
        }
        $img_data = ob_get_clean();
        return $img_data;
    }

    /**
     * 二维码vcard名片
     * @param  [array] $uinfo [名片信息 name姓名* tel_work工作电话 tel_home家庭 email邮箱 company公司 title职称 address地址]
     * @param  string $v     [description]
     * @return [binary]        [图片binary]
     */
    public static function vCard($uinfo, $logo = false, $v = '4.0')
    {
        $vcard = "BEGIN:VCARD\n" .
            "VERSION:{$v}\n" .
            "FN:{$uinfo['name']}\n";
        $uinfo['title'] and $vcard .= "TITLE:{$uinfo['title']}\n";
        $uinfo['tel_work'] and $vcard .= "TEL;TYPE=work,voice:+86{$uinfo['tel_work']}\n";
        $uinfo['tel_home'] and $vcard .= "TEL;TYPE=home,voice:+86{$uinfo['tel_home']}\n";
        $uinfo['email'] and $vcard .= "EMAIL:{$uinfo['email']}\n";
        $uinfo['company'] and $vcard .= "ORG:{$uinfo['company']}\n";
        $uinfo['address'] and $vcard .= "ADR:{$uinfo['address']}\n";
        $vcard .= "END:VCARD";
        
        if(empty($logo))
            $logo = dirname(THINK_PATH).'/Public/images/fg_logo.jpg';

        return self::img($vcard, $logo, 8);
    }
}
